<template>
    <div class="ele-body">
      <!-- 搜索表单 -->
      <recreceiptSearch @search="reload"  />
      <!-- 数据表格 -->
      <el-card shadow="never">
        <ele-pro-table
          ref="table"  row-key="id" :columns="columns" :datasource="datasource"  :need-page="true" :cell-style="cellStyle"  @done="onDone"  :height="tableHeight" :full-height="tableFullHeight"
        >
          <!-- 表头工具栏 -->
          <template slot="toolbar">
            <!-- <el-button
              size="small"
              type="primary"
              icon="el-icon-plus"
              class="ele-btn-icon"
              @click="openEdit({})"
            >
              新增
            </el-button> -->
            <el-button
            v-permission="'Financial_Recreceipt_Export'"
              size="small"
              icon="el-icon-upload2"
              class="ele-btn-icon"
              @click="reportexcel"
            >
              导出
            </el-button>
            <el-upload  ref="upload" size="small" :show-file-list="false" style="display: inline; margin-left: 10px;" action="#" :auto-upload="false" :on-change="handleChange" :limit="1">
              <el-button type="button" size="small"  v-permission="'Financial_Recreceipt_Import'"
                  class="ele-btn-icon">
                  <i class="el-icon-download"></i><span>导入 </span>
              </el-button>
            </el-upload> &nbsp;
            <el-button
            v-permission="'Financial_Recreceipt_ImportTemp'"
              size="small"
              icon="el-icon-download"
              class="ele-btn-icon"
              @click="download"
            >
              导入模板下载
            </el-button>
            <div class="ele-space" style="float: right; margin-top: 5px;">
              <div class="list-tool-item" style="margin-right: 5px;">
                <span>作废数据</span>&nbsp;
                <el-switch
                  :active-value= 1
                  :inactive-value= 0
                  v-model="isDeleted"
                  @change="editState"
                  >
            </el-switch>
              </div>
              <div class="list-tool-divider" style="margin-right: 5px;">
                <el-divider direction="vertical" />
              </div>
          </div>
          </template>
          <template slot="status" slot-scope="{ row }">
            <el-tag type="danger" v-if="row.status==1">{{ row.statusDesc }}</el-tag>
            <el-tag type="success" v-else-if="row.status==5">{{ row.statusDesc }}</el-tag>
          </template>
           <!-- 操作列 -->
         <template slot="action" slot-scope="{ row }"  >
           <el-popconfirm v-show=" row.deleted!=1"  class="ele-action" title="确定要作废吗？"  @confirm="remove(row)" >
            <el-link type="danger" v-permission="'Financial_Recreceipt_Deleted'" slot="reference" :underline="false"  icon="el-icon-delete" >作废</el-link>
          </el-popconfirm>
          
        </template>
        </ele-pro-table>
      </el-card>
       <!-- 编辑弹窗 -->
      <recreceiptauitList :visible.sync="showEdit"  />
      <!-- 导出数据 -->
      <ExportDialog ref="ExportDialog"></ExportDialog>
    </div>
  </template>
  <script>
    
    import ExportDialog from '@/components/Excel/ExportDialog'
    import recreceiptSearch from './components/recreceipt-search.vue';
    import recreceiptauitList from './components/recreceiptauit-list.vue';
    import { QueryRecreceiptitemByCondition,DeleteRecreceiptItem,ImportExcel } from '@/api/finance/recreceipt';

    export default {
      name: 'Recreceipt',
      components: {recreceiptSearch,recreceiptauitList,ExportDialog},
      data() {
        return {
          // 表格列配置
          columns: [
            {columnKey: 'index', type: 'index', width: 50, align: 'center', showOverflowTooltip: true, fixed: 'left', label:'序号',},
            {prop: 'orderNo', label: '业务单号', showOverflowTooltip: true, sortable: 'orderNo',align: 'center',},
            // {prop: 'orderTypeDesc', label: '业务类型', showOverflowTooltip: true,align: 'center',sortable:'orderType'},
            {prop: 'customerName', label: '客户名称', showOverflowTooltip: true,align: 'center',sortable:'customerId'},
            {prop: 'amount', label: '收款金额', showOverflowTooltip: true,align: 'center',sortable:'auitAmount'},
            // {prop: 'auitAmountCn', label: '收款金额(￥)',width: 150, showOverflowTooltip: true,align: 'center',sortable:'auitAmountCn'},
            {prop: 'currencyDesc', label: '币种', showOverflowTooltip: true,align: 'center',sortable:'currencyId'},
            {prop: 'rate', label: '汇率', showOverflowTooltip: true,align: 'center',sortable:'rate'},
            {prop: 'bankAccountDesc', label: '收款账户', showOverflowTooltip: true,align: 'center',sortable:'bankAccountId'},
            {
              prop: 'recDate', label: '收款日期', showOverflowTooltip: true, align: 'center',sortable: 'recDate',
              formatter: (row, column, cellValue) => {return this.$util.toDateString(cellValue,"YYYY-MM-DD");}
            },
            {columnKey: 'action', label: '操作',width: 200,align: 'center',slot:'action', resizable: false, hideInSetting: true, showOverflowTooltip: true,fixed: 'right', }
          ],
          isDeleted: 0,
          //是否详情
          fixedHeight:true,
          // 当前编辑数据
          current: null,
          // 是否显示编辑弹窗
          showEdit: false,
          // 导出列
          exportList: [
            { name: "业务单号", keys: "orderNo", status: true },
            // { name: "业务类型", keys: "orderTypeDesc", status: true },
            { name: "客户名称", keys: "customerName", status: true },
            { name: "收款金额", keys: "amount", status: true },
            { name: "收款金额(￥)", keys: "amountCn", status: true },
            { name: "币种", keys: "currencyDesc", status: true },
            { name: "汇率", keys: "rate", status: true },
            { name: "收款账户", keys: "bankAccountDesc", status: true },
            { name: "收款日期", keys: "recDate", status: true },
          ]
        };
      },
      computed: {
        // 表格高度
        tableHeight() {
          var fh = this.fixedHeight ? 'calc(100vh - 250px)' : void 0;

          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 126px)' : null;

          return fh;
        },
      },
      created(){
        this.receiptNo = this.$route.query.receiptNo;
      },
      methods: {
        /* 表格数据源 */
        async datasource(params) {
          params.where.pageindex = params.page;
          params.where.pagesize = params.limit;
  
          //添加排序
          if(params.order.order == null || params.order.order == undefined){
            params.where.orderBys = [{ sort: "createDate", order: 1, }];
          }else{
            params.where.orderBys = [];
            params.where.orderBys.push({sort:params.sorter.column.sortable,order:params.order.order=='asc'?0:1});
          }

          if(!params.where.conditions)params.where.conditions= [];

          // 结算类型:1 货款收款
          params.where.conditions.push({
            key:"recreceiptType",
            operator: 0,
            value: 1,
          })

          let delIndex = params.where.conditions.findIndex((g)=>{
            return g.key == 'deleted';
          })

          if(delIndex>=0){
            params.where.conditions.splice(delIndex,1)
            params.where.conditions.push({ key:"deleted", operator: 0, value: this.isDeleted})
          }else{
            params.where.conditions.push({
              key:"deleted",
              operator: 0,
              value: this.isDeleted,
            });
          }
        
          let data = await QueryRecreceiptitemByCondition(params.where);

          if(data && data.items){
            data.items.map((m)=>{
              m.grey = this.isDeleted;
            })
          }

          this.$nextTick(() => {
            this.$refs.table.doLayout();
          });
          
          return {
              list:data.items,
              count:data.totalrecords,
          };
        },

        editState(){
          this.reload();
        },
  
        /* 表格渲染完成回调 */
        onDone({ data }) {
          this.supplierList = data;
        },

        /* 刷新表格 */
        reload(where) {
          this.$refs.table.reload({ where: where });
        },
        
        /**
         * 显示编辑
         * @param row 当前行对像
         */
        openEdit(row) {
          this.current = row;
          this.showEdit = true;
        },

        /* 删除 */
        remove(row) {
          const loading = this.$loading({ lock: true });
          DeleteRecreceiptItem(row.id)
            .then((msg) => {
              loading.close();
              this.$message.success(msg);
              this.reload();
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        },

        //导入
        handleChange(file) {
          let obj = {
            file: file.raw, // 文件流
            fileName: file.name, // 文件名称
            fileType: 2, // 文件类型(1:图片,2:文件)
          }
          this.uploadExeclPorts(obj);
        },

        async uploadExeclPorts(obj) {
          let param2 = new FormData();
          param2.append('file', obj.file);

          ImportExcel(param2).then((d)=>{

            if(d.code == 200){
              this.$message.success(d.msg);

            }else{
              
              if(d.data== null || d.data ==''){
                this.$message.error(d.msg);
                }else{
                this.$confirm('数据导入异常,请下载异常信息', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.downloadExeclError(d.data);
                }).catch(() => {
                          
                });
              }
            }
            
            this.reload();
            this.$refs["upload"].clearFiles();

          }).catch(e => {
            this.$message.error(e)
            this.reload();
            this.$refs["upload"].clearFiles();
          });
        },

        downloadExeclError(url) {
          let a = document.createElement('a')
          a.href = url
          a.download = '收款单异常.xls'
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
        },

        /*下载模板*/
        download(row){
          let a = document.createElement('a')
          a.href = "http://47.120.36.89:8091/file/importtemplates/recreceipt.xls";
          a.download = '收款单模板.xlsx'
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          a.remove()
        },

        /* 导出 */
        reportexcel(pams) {

          //初始化参数
          let params = {
            pagesize: 0,
            pageindex: 1,
            conditions: [],
            orderBys: [{ sort: "createDate", order: 1, }],
          };
          //加载进度条
          const loading = this.$loading({ lock: true });
          //重新请求查询
          this.$refs.table.doRequest(({ where }) => {
          if(where){
            params.orderBys = where.orderBys;
            params.pageindex = where.pageindex;
            params.conditions = where.conditions;
          }
          //查询数据
          QueryRecreceiptitemByCondition(params)
            .then((data) => {
              loading.close();
              this.$refs.ExportDialog.showEdits = true
              this.$refs.ExportDialog.checkList = this.exportList
              this.$refs.ExportDialog.titleName = "收款单列表"
              this.$refs.ExportDialog.dataList = data.items;
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
          });
        },

        /* 样式 */
        cellStyle(param){
          let cellStyle;
          const { row, column, rowIndex, columnIndex } = param;
          switch(row.grey == 1){
            case true:
              cellStyle = 'background-color: RGB(240,242,245)';
              break;
            default:
              if(columnIndex==4||columnIndex==3||columnIndex==6||columnIndex==7){
                cellStyle = '';
              }
              break;
          }
          return cellStyle;
        },
      }
    };
  </script>
   <style lang="scss" scoped>
    /*总计字体颜色
    ::v-deep .el-table__footer-wrapper tbody td {
      color: var(--color-primary);
      cursor: pointer;
    }*/
  </style>